package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import com.atguigu.gmall.product.model.BaseAttrInfo;
import com.atguigu.gmall.product.model.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 *
 * @author XIN
 * 2023/4/17
 */
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper,BaseAttrInfo> implements BaseAttrInfoService {
	@Autowired
	private BaseAttrValueService baseAttrValueService;
	/**
	 * 根据多个 三级分类ID 查询当前分类包含平台属性名列表
	 * @param category1Id
	 * @param category2Id
	 * @param category3Id
	 * @return
	 */
	@Override
	public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
		BaseAttrInfoMapper baseMapper1 = this.getBaseMapper();
		System.out.println("--------------------------");
//		System.err.println(baseMapper1);
//		System.err.println(baseMapper);
		System.out.println("++++++++++++++++++++++++++");
		return baseMapper1.getAttrInfoList(category1Id,category2Id,category3Id);
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveAttrInfo(BaseAttrInfo base) {
		if(base.getId() ==null){
			this.save(base);
			List<BaseAttrValue> attrValueList = base.getAttrValueList();
			if (!CollectionUtils.isEmpty(attrValueList)){
				for (BaseAttrValue baseAttrValue : attrValueList) {
					baseAttrValue.setAttrId(base.getId());
				}
				baseAttrValueService.saveBatch(attrValueList);
			}
		}else {
			this.updateById(base);
			LambdaQueryWrapper<BaseAttrValue> queryWrapper =new LambdaQueryWrapper<>();
			queryWrapper.eq(BaseAttrValue::getAttrId,base.getId());
			baseAttrValueService.remove(queryWrapper);
			List<BaseAttrValue> attrValueList = base.getAttrValueList();
			if (!CollectionUtils.isEmpty(attrValueList)){
				attrValueList.stream().forEach(baseAttrValue -> {
					baseAttrValue.setAttrId(base.getId());
				});
				baseAttrValueService.saveBatch(attrValueList);
			}
		}
	}
	
	@Override
	public List<BaseAttrValue> getAttrValueList(Long attrId) {
		LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(BaseAttrValue::getAttrId, attrId);
		return baseAttrValueService.list(queryWrapper);
	}
	
}
